package com.eystar.pdc.aop.log;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.eystar.ext.kit.Ip2RegionKit;
import com.eystar.ext.kit.RequestKit;
import com.eystar.pdc.model.Log;
import com.eystar.pdc.model.User;
import com.eystar.pdc.util.LoginUtil;
import com.eystar.pdc.util.PdcHelper;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Log4jLog;

import cn.hutool.core.util.StrUtil;

/**
 * 记录日志的Interceptor
 * 
 * @author auth
 * 
 */
public class LogInterceptor implements Interceptor {
	protected final Log4jLog logger = Log4jLog.getLog(LogInterceptor.class);

	@Override
	public void intercept(Invocation ai) {
		HttpServletRequest request = ai.getController().getRequest();

		Method method = ai.getMethod();
		// 如果有注释的话，需要记录日志。
		if (method.isAnnotationPresent(LogAnno.class)) {
			LogAnno logAnno = method.getAnnotation(LogAnno.class);
			String desc = logAnno.desc();
			if (desc.indexOf("$") > -1) { // 说明存在变量
				String var = StrUtil.subBetween(desc, "{", "}");
				String varValue = request.getParameter(var);
				if (StrUtil.startWith(var, "session.")) { // 如果配置了从session中获取信息
					varValue = (String) request.getSession().getAttribute(var.replace("session.", ""));
				}
				desc = StrUtil.replace(desc, "${" + var + "}", varValue);
			}
			short status = LoginUtil.SUCCESS;
			String createUser = null;
			try {
				// 如果是退出方法的话，先获取用户名字，否则的话用户名字就被注销掉了，没有办法获取了。
				if (StrUtil.equals(method.getName(), "logout")) {
					createUser = PdcHelper.getCurrentUserName(request);
				}
				// 如果是登录的话，要从请求中获取登录用户的信息
				if (StrUtil.equals(method.getName(), "doLogin")) {
					createUser = request.getParameter("user.user_name");
				}
				ai.invoke();
			} catch (Exception e) {
				status = LoginUtil.FAILURE;
				// 如果是ajax请求的话，将使用Controller中返回的结果，所以必须不能抛出异常。
				if (!RequestKit.isAjaxRequest(request)) {
					throw new RuntimeException(e);
				}
			} finally {
				saveLog(request, desc, status, createUser,logAnno.type().getValue());
			}
		} else {
			ai.invoke();
		}
	}

	/**
	 * 保存日志
	 * @param request
	 * @param desc
	 * @param status
	 * @param createUser
	 */
	public void saveLog(HttpServletRequest request, String desc, short status, String createUser,short logOp) {
		Log log = new Log();
		User user = PdcHelper.getCurrentUser(request);
		log.set("log_desc", desc);
		String ip = RequestKit.getIpAddress(request);
		log.set("log_ip", ip);
		log.set("log_op", logOp);
		log.set("ip_location", Ip2RegionKit.getBtreeRegion(ip));
		log.set("log_url", request.getRequestURI());
		log.set("status", LoginUtil.SUCCESS);
		log.set("create_time", new Date().getTime()/1000);
		log.set("create_user", StrUtil.isNotBlank(createUser) ? createUser : (user == null ? null : user.getStr("user_name")));
		ThreadLog.add(log);
	}
}
